<template>
  <div class="home">
    <div class="main-bg-color head">
      <div class="d-flex a-center px-2 header" style="height:8vh;white-space: nowrap;">
        <div class="font-weight font-lg text-fff" v-if="this.role == 'ROLE_PHARMACY'">药店平台</div>
        <div class="font-weight font-lg text-fff" v-if="this.role == 'ROLE_ADMIN'">超管平台</div>
        <div class="font-weight font-lg text-fff" v-if="this.role == 'ROLE_EXAMINE'">审核平台</div>
        <div class="nav" v-show="isUser">
          <el-menu
            :default-active="String(activeIndex)"
            class="el-menu-demo"
            mode="horizontal"
            @select="handleSelect"
            background-color="#0882f4"
            text-color="#fff"
            active-text-color="#fff"
          >
            <el-menu-item
              v-for="(item,index) in menuList"
              :key="index"
              :index="String(index)"
              @click="changeNav(item)"
            >{{item.name}}</el-menu-item>
          </el-menu>
        </div>
        <div class="userInfo">
          <div class="msgNum" @click="msgDialog">
            <el-badge :value="msgNum" :max="99" class="item">
              <i class="el-icon-message" style="fontSize:28px;color:#fff;"></i>
            </el-badge>
          </div>
          <div class="headPhoto">
            <img src alt />
          </div>
          <el-dropdown>
            <div class="nickName">
              {{nickName}}
              <i class="el-icon-arrow-down el-icon--right"></i>
            </div>
            <el-dropdown-menu slot="dropdown" style="width:200px">
              <div class="medInfo">
                <div class="logo">
                  <img src alt />
                </div>
                <div class="medName">国盛大药房</div>
              </div>
              <div class="infoList">
                <div class="infoItem" @click="info">基本资料</div>
                <div class="line" style="margin:0 5px">|</div>
                <div class="infoItem">资质信息</div>
                <div class="line" style="margin:0 5px">|</div>
                <div class="infoItem">法人信息</div>
              </div>
              <div class="exitLogin">
                <div class="indexPage" @click="indexPage" v-show="!isUser">首页</div>
                <img @click="exit" :src="require(`../../public/static/img/${app}/exit.png`)" alt />
                <span @click="exit">退出登录</span>
              </div>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
    </div>
    <div class="d-flex" style="position:absolute;top:8vh;bottom:0;width:100%;">
      <div class="sidebar" v-show="isUser">
        <div class="title">{{sidebarObj.name}}</div>
        <div class="ul">
          <div
            v-for="(item,index) in sidebarObj.childLs"
            :key="index"
            :class="selectNum==item.id?'selected':'item'"
          >
            <div class="childItem" @click="goUrl(item.href)">{{item.name}}</div>
          </div>
        </div>
      </div>
      <div :class="isUser?'nomal':'spca'" style="height:100%;overflow:scroll">
        <div class="d-flex a-center p-3">
          <div style="width:5px;height:25px;" class="main-bg-color"></div>
          <div class="font-weight ml-1" style="font-size:18px">{{$route.name}}</div>
        </div>
        <router-view class="px-3"></router-view>
      </div>
    </div>
    <el-drawer
      type="primary"
      :with-header="false"
      :visible.sync="drawer"
      :before-close="handleClose"
      size="50%"
    >
      <div style="textAlign:center;height:60px;lineHeight:60px;fontSize:18px">收件箱</div>
      <el-collapse v-model="activeNames">
        <el-collapse-item
          v-for="(item,index) in msgList"
          :key="index"
          :name="index+1"
          @click.native="messageCollapseChangeEvent(item)"
        >
          <template slot="title">
            <span :class="item.isRead==1?'noread':'read'">{{item.msgTitle}}</span>
            <i
              v-if="item.isRead==2"
              class="el-icon-document-checked"
              style="color:green;marginLeft:5px"
            ></i>
            <i
              v-if="item.isRead==1"
              class="el-icon-document-delete"
              style="color:red;marginLeft:5px"
            ></i>
          </template>
          <div style="marginRight:10px">{{item.msgSender}}：{{item.msgContent}}</div>
          <div style="textAlign:right;marginRight:10px">{{item.msgReseiver}}</div>
        </el-collapse-item>
        <div class="block">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="pageInfo.total"
            @current-change="getMsgList($event)"
          ></el-pagination>
        </div>
      </el-collapse>
    </el-drawer>
  </div>
</template>

<script>
import { formatTimeToStr } from "../util/date";
export default {
  inject: ["reload"],
  data() {
    //心跳检测
    return {
      role: sessionStorage.getItem("role"),
      nickName: sessionStorage.getItem("username"),
      currentIndex: 0,
      activeIndex: 0,
      currentPage: 1,
      menuList: [],
      sidebarObj: {},
      selectNum: null,
      circleUrl: "",
      sizeList: ["large", "medium", "small"],
      isUser: true,
      drawer: false,
      activeNames: [],
      msgNum: 0,
      pageInfo: {}, //信息分页信息
      msgList: [], //个人消息集合
      lockReconnect: false,
      timeout: 9000,        //9分钟发一次心跳
      timeoutObj: null,
      serverTimeoutObj: null,
    };
  },
  watch: {
    $route(cur, old) {
      if (cur.fullPath == "/userInfo") {
        this.isUser = false;
      } else {
        this.isUser = true;
      }
      this.sidebarObj.childLs.map(e => {
        if (e.href == cur.fullPath) {
          this.selectNum = e.id;
        }
      });
    }
  },
  created() {
    this.post(
      "/common/getMenu",
      { roleId: sessionStorage.getItem("roleId") },
      res => {
        if (res.code && res.code == 200) {
          let obj = {};
          if (
            sessionStorage.getItem("userId") == 1 ||
            sessionStorage.getItem("userId") == 3
          ) {
            res.data.map((e, i) => {
              if (e.id == "5") {
                obj = e;
                res.data.splice(i, 1);
              }
            });
          } else {
            res.data.map((e, i) => {
              if (e.id == "5") {
                obj = e;
                res.data.splice(i, 1);
              } else if (e.id == "1") {
                e.name = "历史申请";
              }
            });
          }
          if (obj !== {}) {
            res.data.unshift(obj);
          }
          this.menuList = res.data;
          if(sessionStorage.getItem("toUrl")){
            this.goUrl(sessionStorage.getItem("toUrl"));
            this.menuList.forEach((e,i) =>{
              e.childLs.forEach(item =>{
                if(item.href==sessionStorage.getItem("toUrl")){
                  this.sidebarObj = e;
                  this.activeIndex=i
                  this.selectNum=item.id
                }
              })
            })
          }else{
            this.sidebarObj = this.menuList[0];
            this.goUrl(this.sidebarObj.childLs[0].href);
            this.selectNum = this.sidebarObj.childLs[0].id;
          }
          this.getMsgCount();
        }
      },
      false
    );
    this.initWebSocket();
  },
  methods: {
    // menuChange(index) {
    //   if (index != this.currentIndex) {
    //     this.currentIndex = index;
    //     this.$nextTick(() => {
    //       this.activeIndex = 0;
    //     });
    //   }
    // },
    getMsgCount() {
      this.post(
        "/msg/getMsgCount",
        { msgReseiver: this.nickName },
        res => {
          if (res.code && res.code == 200) {
            this.msgNum = res.data;
          }
        },
        false
      );
    },
    messageCollapseChangeEvent(item) {
      let updateDate = formatTimeToStr(new Date(), "yyyy-MM-dd hh:mm:ss");
      if (item.isRead == 1) {
        this.post(
          "/msg/updateMsg",
          { id: item.id, isRead: "2", updateBy: this.nickName, updateDate },
          res => {
            if (res.code == 200) {
              this.msgDialog(this.currentPage);
              this.getMsgCount();
            }
          },
          false
        );
      }
    },
    handleChange(val) {
      console.log(val);
    },
    handleClose(done) {
      this.activeNames = [];
      done();
    },
    selectMenu() {
      console.log(this.activeIndex);
    },
    handleSelect() {},
    goUrl(url) {
      sessionStorage.setItem("toUrl", url);
      this.$router.push(url);
    },
    changeNav(item) {
      this.sidebarObj = item;
      this.goUrl(item.childLs[0].href);
    },
    //退出登陆
    exit() {
      this.$confirm("真的要离开我了吗?", "提示", {
        confirmButtonText: "残忍离开",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          sessionStorage.removeItem("username");
          sessionStorage.removeItem("password");
          sessionStorage.removeItem("userId");
          sessionStorage.removeItem("sessionId");
          sessionStorage.removeItem("role");
          this.websocketclose;
          this.goUrl("/");
        })
        .catch(() => {});
    },
    //个人中心
    info() {
      this.goUrl("/userInfo");
    },
    //首页
    indexPage() {
      this.$router.back();
    },
    //查看信息
    msgDialog() {
      this.drawer = true;
      this.getMsgList(this.currentPage);
    },
    getMsgList(pageNum) {
      this.currentPage = pageNum;
      this.post(
        "/msg/getMsg",
        { msgReseiver: this.nickName, pageNum, pageSize: 10 },
        res => {
          if (res.code && res.code == 200) {
            this.pageInfo = res.data;
            console.log(this.pageInfo);
            this.msgList = res.data.list;
            // this.msgList.forEach((e, i) => {
            //   if (e.isRead == 2) {
            //     this.activeNames.push(i + 1);
            //   }
            // });
          }
        },
        false
      );
    },
    initWebSocket() {
      //初始化weosocket
      if ("WebSocket" in window) {
        const wsuri = this.websocketUrl + this.nickName; //ws地址
        this.websock = new WebSocket(wsuri);
        this.websock.onopen = this.websocketonopen;
        this.websock.onerror = this.websocketonerror;
        this.websock.onmessage = this.websocketonmessage;
        this.websock.onclose = this.websocketclose;
      } else {
        this.$message.warning("您的浏览器不支持WebSocket");
        this.isWebSocket = false;
      }
    },
    websocketonopen() {
      this.reset();
      this.start();
      console.log("WebSocket连接成功");
    },
    websocketonerror(e) {
      //错误
      console.log(JSON.stringify(e));
      console.log("WebSocket连接发生错误");
    },
    websocketonmessage(e) {
      this.reset();
      this.start();
      //数据接收
      //let redata = JSON.parse(e.data);
      //注意：长连接我们是后台直接1秒推送一条数据，
      //但是点击某个列表时，会发送给后台一个标识，后台根据此标识返回相对应的数据，
      //这个时候数据就只能从一个出口出，所以让后台加了一个键，例如键为1时，是每隔1秒推送的数据，为2时是发送标识后再推送的数据，以作区分
      //console.log(e);
      let self = this;
      if (e.data == 'ping'){
        console.log('心跳检测，'+ new Date().toUTCString())
      } 
      if (e.data == 'newmsg'){
        self.msgNum++;
        this.$notify.info({
          title: '消息提醒',
          message: '你有新消息了，请查看',
          position: 'bottom-right',
          onClick: function() {
                self.msgNum--;
                self.msgDialog();
          },
        });
      } 
    },
    websocketsend(agentData) {
      //数据发送
      this.websock.send(agentData);
    },

    websocketclose(e) {
      //关闭
      console.log(JSON.stringify(e));
      console.log("connection closed (" + e.code + ")");
    },
    reconnect() {
      if(this.lockReconnect) return;
      this.lockReconnect = true;
      setTimeout(function () {     //没连接上会一直重连，设置延迟避免请求过多
          this.initWebSocket();
          this.lockReconnect = false;
      }, 2000);
    }, 
    reset(){
            clearTimeout(this.timeoutObj);
            clearTimeout(this.serverTimeoutObj);
            return this;
        },
    start(){
        var self = this;
        this.timeoutObj = setTimeout(function(){
            //这里发送一个心跳，后端收到后，返回一个心跳消息，
            //onmessage拿到返回的心跳就说明连接正常
            self.websocketsend("ping");
            console.log("ping!")
            self.serverTimeoutObj = setTimeout(function(){//如果超过一定时间还没重置，说明后端主动断开了
                self.websocketclose();     //如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
            }, self.timeout)
        }, this.timeout)
    },
  }
};
</script>

<style lang="less" scoped>
.home {
  width: 100%;
  height: 100%;
}
.menu-item {
  color: #fff;
  cursor: pointer;
}
.menu-item:hover {
  color: #ccc;
}
.el-menu-item.is-active {
  background: rgba(255, 255, 255, 0.2) !important;
}
.header {
  display: flex;
  justify-content: space-between;
  .nav {
    height: 100%;
    .el-menu.el-menu--horizontal {
      height: 100%;
    }
    .el-menu-demo el-menu--horizontal el-menu {
      display: table;
    }
    .el-menu-item {
      min-width: 100px !important;
      text-align: center;
      line-height: 75px;
      font-size: 14px;
      height: 100%;
      display: table-cell;
    }
  }
  .userInfo {
    display: flex;
    justify-content: space-around;
    align-items: center;
    .msgNum {
      cursor: pointer;
      margin-right: 30px;
    }
    .headPhoto {
      width: 40px;
      height: 40px;
      margin-right: 5px;
      border-radius: 50%;
      background-color: #fff;
      overflow: hidden;
    }
    .nickName {
      color: #fff;
    }
  }
}
.medInfo {
  display: flex;
  align-items: center;
  padding: 0 10px;
  .logo {
    width: 30px;
    height: 30px;
    margin-right: 12px;
    border-radius: 50%;
    background-color: #000;
    overflow: hidden;
  }
  .medName {
    font-size: 12px;
  }
}
.infoList {
  padding: 0 10px 20px 10px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: space-around;
  font-size: 10px;
  color: #ccc;
  margin-top: 20px;
  border-bottom: 1px #ccc solid;
  .infoItem {
    &:hover {
      color: #0882f4;
      cursor: pointer;
    }
  }
}
.exitLogin {
  padding: 5px 5px 0 0;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  font-size: 12px;
  .indexPage {
    margin-right: 70px;
    &:hover {
      color: #0882f4;
      cursor: pointer;
    }
  }
  img {
    margin-right: 4px;
  }
  span {
    &:hover {
      color: #0882f4;
      cursor: pointer;
    }
  }
}
.sidebar {
  width: 12%;
  min-width: 150px;
  height: 100%;
  background-color: rgba(42, 55, 79, 1);
  color: #8e97a8;
  .title {
    text-align: center;
    font-weight: 700;
    font-family: "Arial Negreta", "Arial Normal", "Arial";
    color: #8e97a8;
    padding: 20px;
    letter-spacing: 2px;
  }
  .ul {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    letter-spacing: 1px;
    .item {
      width: 100%;
      height: 40px;
      line-height: 40px;
      text-align: center;
    }
    .selected {
      width: calc (100% - 5px);
      text-align: center;
      color: rgba(255, 255, 255, 1);
      background-color: rgba(0, 0, 0, 1);
      border-right: 5px #0882f4 solid;
    }
    .childItem {
      cursor: pointer;
      height: 40px;
      line-height: 40px;
    }
  }
}
.nomal {
  width: 88%;
}
.spca {
  width: 100%;
}
/deep/.el-collapse-item__header {
  font-size: 15px;
  padding: 0 0 0 20px !important;
}
/deep/.el-collapse-item__content {
  padding: 0 0 20px 20px !important;
}
.noread {
}
.read {
  color: #ccc;
}
/deep/.el-drawer {
  overflow: scroll !important;
  padding-bottom: 20px;
}
</style>
